//
//  AppDelegate.m
//  ESTSCRMAPP
//
//  Created by 李贤立 on 2018/9/20.
//  Copyright © 2018年 Capfer. All rights reserved.
//

#import "AppDelegate.h"
#import "TYZNavigationController.h"
#import "TYZTabBarController.h"
#import "ESTLoginViewController.h"
#import "ESTActivityViewController.h"
#import <UMMobClick/MobClick.h>
#import <UserNotifications/UserNotifications.h>
#define UMAppKeyForESTSCRMApp         @"5bd6d9d3f1f556630500003b"
@interface AppDelegate () <UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 基本信息初始化
    [TYZCoreInfo initial];
    // 统计
    [self UMAnalytics];
    [NSThread sleepForTimeInterval:0.5];
    // 设置窗口
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    self.window.rootViewController = [[TYZNavigationController alloc] initWithRootViewController:[[ESTLoginViewController alloc] init]];

    [[UIApplication sharedApplication] registerForRemoteNotifications];
    if (@available(iOS 10.0, *)) {
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    } else {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
    
    return YES;
}

- (void)UMAnalytics {
    UMConfigInstance.appKey = UMAppKeyForESTSCRMApp;
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // 后台继续运行
    __block UIBackgroundTaskIdentifier bgTask;
    
    bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if(bgTask != UIBackgroundTaskInvalid) {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if(bgTask != UIBackgroundTaskInvalid) {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
}

#pragma mark ------------------------------推送处理--------------------------------------------
//app允许接受远程通知以后利用该回调回取token
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
    NSString *deviceTokenString = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"withString:@""]
                                   stringByReplacingOccurrencesOfString:@">"withString:@""]
                                  stringByReplacingOccurrencesOfString:@" "withString:@""];
    
    CoreInfo.deviceToken = deviceTokenString;
    NSLog(@"本地存储deviceToken = %@", deviceTokenString);
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_GetDeviceTokenSuccess object:deviceTokenString];
}

//app允许接受远程通知以后token获取失败
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
    NSLog(@"DeviceToken获取失败，原因：%@",error);
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_GetDeviceTokenFailure object:nil];
}
@end
